//=========================================================================
// Copyright (C) 2024 The C++ Component Model(COMO) Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================

// #include <sys/socket.h>  // socket()、sockaddr、bind()、recvfrom()、sendto()
#include <stdio.h>          //(perror())、printf()
#include <stdlib.h>         //exit()
// #include <netinet/in.h>  //sockaddr_in、（htons()）
#include <string.h>         //bzero()、strncpy()
#include <arpa/inet.h>      //inet_pton()
#include <unistd.h>         //close()
#include <stdint.h>
#include "rudp.h"
#include "comm.h"

// macros are defined in comm.h
// global variables (defined in comm.c)
extern Rudp rudp;
extern int sock_fd;
extern struct sockaddr_in serv_addr; // server socket struct
extern char msg_send[g_buff_size];   // msg buffer sent to client
extern char msg_recv[g_buff_size];   // msg buffer received from client

int main(int arg, char *argv[])
{
    Rudp *U = RudpNew(&rudp, 1, 5);

    // test data
    // in our case, server send r1-r4 & receive t1-t4
    char r1[] = { 02, 00, 00, 02, 00, 03 };
    char r2[] = { 5, 0, 1, 1,
                  5, 0, 3, 3,
                };
    char r3[] = { 5, 0, 0, 0,
                  5, 0, 5, 5,
                };
    char r4[] = { 5, 0, 2, 2 };

    // init socket
	socket_init(CALL_BY_SERVER, g_serv_port);

    // receive t1-t4
    for (int i=0;i<4;i++){
        size_t size_recv = udp_recv(CALL_BY_SERVER);
        RudpUpdate(U, msg_recv, (int)size_recv, 1);
        dump_recv(U);
    }

    // send r1-r4
    RudpSend(U, r1, sizeof(r1));
    udp_send(RudpUpdate(U, NULL, 0, 1), CALL_BY_SERVER);
    RudpSend(U, r2, sizeof(r2));
    udp_send(RudpUpdate(U, NULL, 0, 1), CALL_BY_SERVER);
    RudpSend(U, r3, sizeof(r3));
    udp_send(RudpUpdate(U, NULL, 0, 1), CALL_BY_SERVER);
    RudpSend(U, r4, sizeof(r4));
    udp_send(RudpUpdate(U, NULL, 0, 1), CALL_BY_SERVER);

    // end
    socket_close();
    RudpDelete(U);

    return 0;
}